package com.daxilong.starchen.player;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentTransaction;

import com.daxilong.starchen.player.activity.SearchActivity;
import com.daxilong.starchen.player.databinding.ActivityMainBinding;
import com.daxilong.starchen.player.fragment.AudioFragment;
import com.daxilong.starchen.player.fragment.LocalAudioFragment;
import com.daxilong.starchen.player.fragment.LocalVideoFragment;
import com.daxilong.starchen.player.fragment.NetVideoFragment;
import com.google.android.material.navigation.NavigationBarView;

@RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
public class MainActivity extends AppCompatActivity {

    private LocalAudioFragment localAudioFragment;
    private AudioFragment audioFragment;
    private LocalVideoFragment localVideoFragment;
    private NetVideoFragment videoFragment;
    private ActivityMainBinding binding;
    private int position = 0;

    private final String[] requiredMinPermission = {android.Manifest.permission.INTERNET,
            android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.VIBRATE,
            android.Manifest.permission.RECORD_AUDIO};

    private final String[] requiredPermission = {android.Manifest.permission.INTERNET,
            android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.READ_PHONE_STATE,
            android.Manifest.permission.ACCESS_WIFI_STATE,
            android.Manifest.permission.ACCESS_NETWORK_STATE,
            android.Manifest.permission.CHANGE_NETWORK_STATE,
            android.Manifest.permission.POST_NOTIFICATIONS,
            android.Manifest.permission.VIBRATE,
            android.Manifest.permission.RECORD_AUDIO};

    private final static int REQ_PERMISSION_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        boolean permission = checkPermission();

        if(permission){
            initView();
            initData();
        }
        else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                // Android 13+ 需要权限
                ActivityCompat.requestPermissions(this,requiredPermission,REQ_PERMISSION_CODE);
            } else {
                ActivityCompat.requestPermissions(this,requiredMinPermission,REQ_PERMISSION_CODE);
            }
        }

    }

    private void initView(){
        //底部导航栏点击事件
        binding.bottomView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                if (item.getItemId() == R.id.local_video) {
                    selectFragment(0);
                } else if (item.getItemId() == R.id.local_music) {
                    selectFragment(1);
                } else if (item.getItemId() == R.id.net_video) {
                    selectFragment(2);
                } else if (item.getItemId() == R.id.net_music) {
                    selectFragment(3);
                }
                return true;
            }
        });

        //游戏
        binding.titlebarTop.ivGame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("MainActivity","游戏");
            }
        });

        //点击搜索栏
        binding.titlebarTop.tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SearchActivity.class);
                startActivity(intent);
            }
        });

        binding.titlebarTop.ivHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("MainActivity","历史");
            }
        });
    }

    private void initData() {
        selectFragment(position);
    }

    private void selectFragment(int position) {
        this.position = position;
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideFragment(transaction);

        if(position == 0){
            if(localVideoFragment == null){
                localVideoFragment = new LocalVideoFragment();
                transaction.add(R.id.content,localVideoFragment);
            }
            else {
                transaction.show(localVideoFragment);
            }
        }
        else if(position == 1){
            if(localAudioFragment == null){
                localAudioFragment = new LocalAudioFragment();
                transaction.add(R.id.content,localAudioFragment);
            }
            else {
                transaction.show(localAudioFragment);
            }
        }
        else if(position == 2){
            if(videoFragment == null){
                videoFragment = new NetVideoFragment();
                transaction.add(R.id.content,videoFragment);
            }
            else {
                transaction.show(videoFragment);
            }
        }
        else if(position == 3){
            if(audioFragment == null){
                audioFragment = new AudioFragment();
                transaction.add(R.id.content,audioFragment);
            }
            else {
                transaction.show(audioFragment);
            }
        }
        transaction.commit();
    }

    private void hideFragment(FragmentTransaction transaction){
        if(localAudioFragment != null){
            transaction.hide(localAudioFragment);
        }

        if(audioFragment != null){
            transaction.hide(audioFragment);
        }

        if(localVideoFragment != null){
            transaction.hide(localVideoFragment);
        }

        if(videoFragment != null){
            transaction.hide(videoFragment);
        }
    }

    /**
     * 检查权限
     */
    private boolean checkPermission() {
        //是否有权限
        boolean allPermissionGranted = true;


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ 需要权限
            for(String permission:requiredPermission){
                if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
                    allPermissionGranted = false;
                    break;
                }
            }
        } else {
            for(String permission:requiredMinPermission){
                if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
                    allPermissionGranted = false;
                    break;
                }
            }
        }
        return allPermissionGranted;
    }

    /**
     * 权限返回处理
     */
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResult) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResult);
        if (requestCode == REQ_PERMISSION_CODE) {
            boolean allGrant = true;
            for(int result : grantResult){
                if(result != PackageManager.PERMISSION_GRANTED){
                    allGrant = false;
                    break;
                }
            }
            if(allGrant){
                initView();
                initData();
            }
            else {
                Toast.makeText(this, "请求权限失败,请重新启动", Toast.LENGTH_SHORT).show();
            }

        }
    }

    private long startTime;
    @Override
    public void onBackPressed() {
        if(position!=0) {
            selectFragment(0);
            return ;
        }
        if(System.currentTimeMillis()-startTime>2000) {
            startTime=System.currentTimeMillis();
            Toast.makeText(MainActivity.this, "再点一次退出", Toast.LENGTH_SHORT).show();
            return ;
        }
        super.onBackPressed();
    }

}

